<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>JS中的闭包问题，闭包的那是些事 | Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="JS的闭包我们可以谈些什么？我刚学js闭包的时候觉得很难去理解，只是知道函数内部的使用了函数外部的变量，但是我后来渐渐深入的了解js…">
<meta property="og:type" content="article">
<meta property="og:title" content="JS中的闭包问题，闭包的那是些事">
<meta property="og:url" content="http://yoursite.com/2020/06/10/JS%E4%B8%AD%E7%9A%84%E9%97%AD%E5%8C%85%E9%97%AE%E9%A2%98%EF%BC%8C%E9%97%AD%E5%8C%85%E7%9A%84%E9%82%A3%E6%98%AF%E4%BA%9B%E4%BA%8B/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="JS的闭包我们可以谈些什么？我刚学js闭包的时候觉得很难去理解，只是知道函数内部的使用了函数外部的变量，但是我后来渐渐深入的了解js…">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2020-06-10T10:42:53.000Z">
<meta property="article:modified_time" content="2020-07-30T13:04:01.601Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  
<link rel="stylesheet" href="/css/style.css">

<meta name="generator" content="Hexo 5.0.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-JS中的闭包问题，闭包的那是些事" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2020/06/10/JS%E4%B8%AD%E7%9A%84%E9%97%AD%E5%8C%85%E9%97%AE%E9%A2%98%EF%BC%8C%E9%97%AD%E5%8C%85%E7%9A%84%E9%82%A3%E6%98%AF%E4%BA%9B%E4%BA%8B/" class="article-date">
  <time datetime="2020-06-10T10:42:53.000Z" itemprop="datePublished">2020-06-10</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      JS中的闭包问题，闭包的那是些事
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>JS的闭包我们可以谈些什么？<br>我刚学js闭包的时候觉得很难去理解，只是知道函数内部的使用了函数外部的变量，但是我后来渐渐深入的了解js…</p>
<a id="more"></a>
<h4 id="一-、闭包与执行上下文"><a href="#一-、闭包与执行上下文" class="headerlink" title="一 、闭包与执行上下文"></a>一 、闭包与执行上下文</h4><p> &ensp;&ensp;&ensp;首先在深入了解js闭包之前，我们必须要知道函数的作用域，以及执行上下文,执行上下文通俗的讲就是函数在被创建的时候产生的执行环境的概念，js中的任何代码都是在执行上下文运行的。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="function"><span class="title">aa</span></span>() &#123;</span><br><span class="line">         var a = 123;</span><br><span class="line">     <span class="keyword">function</span> <span class="function"><span class="title">bb</span></span>() &#123;</span><br><span class="line">             a++;</span><br><span class="line">             console.log(a);</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="built_in">return</span> bb;</span><br><span class="line">     &#125;</span><br><span class="line">     var glob = aa(); // glob是aa内容<span class="built_in">return</span>的函数体，外部函数已经运行完毕，但是变量仍被内部函数引用，故不会被释放</span><br><span class="line">     var demo = glob();</span><br><span class="line">     demo() // 输出a =124</span><br></pre></td></tr></table></figure>
<p> &ensp;&ensp;&ensp;aa在被创建的时候产生的自己的执行上下文，当aa被调用的时候，产生AO,并且当执行完毕时会立刻销毁，由于内部函数在被创建时就有aa提供的AO，仍然使用了a变量所以bb会拿着aa的AO，当bb函数执行时输出为124。</p>
<h4 id="二、闭包的好处"><a href="#二、闭包的好处" class="headerlink" title="二、闭包的好处"></a>二、闭包的好处</h4><h6 id="1-变量可以长期驻扎在内存之中"><a href="#1-变量可以长期驻扎在内存之中" class="headerlink" title="1.变量可以长期驻扎在内存之中"></a>1.变量可以长期驻扎在内存之中</h6><h6 id="2-避免全局变量的污染，有私有成员"><a href="#2-避免全局变量的污染，有私有成员" class="headerlink" title="2.避免全局变量的污染，有私有成员"></a>2.避免全局变量的污染，有私有成员</h6> <figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">demo() // 继续执行时，输出a =125</span><br><span class="line">demo() //  输出a =126    </span><br></pre></td></tr></table></figure>
<p>  继续执行了上面的代码发现a会被累加。</p>
<h4 id="三、闭包的用途"><a href="#三、闭包的用途" class="headerlink" title="三、闭包的用途"></a>三、闭包的用途</h4>  <figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">  var arr=[];</span><br><span class="line"><span class="keyword">function</span> <span class="function"><span class="title">foo</span></span>()&#123;</span><br><span class="line">   <span class="keyword">for</span> (var i=0;i&lt;3;i++)&#123;</span><br><span class="line">        arr[i]=<span class="function"><span class="title">function</span></span>()&#123;</span><br><span class="line">            alert(i)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line">foo();</span><br><span class="line">arr[0](); // 3</span><br><span class="line">arr[1](); // 3</span><br><span class="line">arr[2](); // 3</span><br></pre></td></tr></table></figure>
<p>&ensp;&ensp;&ensp;这段代码对于新手理解起来应该是比较困难的。外部函数执行完后i=3，由于内部函数引用了外部变量arr，执行完foo后不会被立即销毁，当执行内部函数时，会使用其外部函数的AO中的i，此时i=3，所以再次调用了内部函数时结果都为3。下面我来使用闭包来修改下代码。<br> <figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">var arr=[];</span><br><span class="line">    <span class="keyword">function</span> <span class="function"><span class="title">foo</span></span>()&#123;</span><br><span class="line">        <span class="keyword">for</span> (var i=0;i&lt;3;i++)&#123;</span><br><span class="line">            (<span class="keyword">function</span>(index)&#123;</span><br><span class="line">                arr[i]=<span class="function"><span class="title">function</span></span>()&#123;</span><br><span class="line">                    alert(index);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;)(i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    foo();</span><br><span class="line">arr[0](); // 0</span><br><span class="line">arr[1](); // 1</span><br><span class="line">arr[2](); // 2</span><br></pre></td></tr></table></figure><br>&ensp;&ensp;&ensp;这种写法有一个好处，仔细的同学能看到我在内部写了一个匿名函数。我们创建了一个匿名的函数，并立即执行它，由于外部无法引用他的内部变量，因此在函数执行完之后会立即释放资源，关键是不污染全局变量。</p>
<h5 id="再说闭包最后的一个用途"><a href="#再说闭包最后的一个用途" class="headerlink" title="再说闭包最后的一个用途"></a>再说闭包最后的一个用途</h5><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">var person = <span class="function"><span class="title">function</span></span>() &#123;</span><br><span class="line">          //变量作用域为函数内部，外部无法访问    </span><br><span class="line">          var name = <span class="string">&quot;zhu&quot;</span>;</span><br><span class="line">          <span class="built_in">return</span> &#123;</span><br><span class="line">              getName: <span class="function"><span class="title">function</span></span>() &#123;</span><br><span class="line">                  <span class="built_in">return</span> name;</span><br><span class="line">              &#125;,</span><br><span class="line">              setName: <span class="keyword">function</span>(newName) &#123;</span><br><span class="line">                  name = newName;</span><br><span class="line">              &#125;</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;();</span><br><span class="line"></span><br><span class="line">      alert(person.name); //直接访问，结果为undefined    </span><br><span class="line">      alert(person.getName()); //结果为zhu    </span><br><span class="line">      person.setName(<span class="string">&quot;abruzzi&quot;</span>);</span><br><span class="line">      alert(person.getName()); //结果为abruzzi</span><br></pre></td></tr></table></figure>
<p>&ensp;&ensp;&ensp;如上述代码，我们可以利用闭包进行<em>函数封装</em>，我们通过return方式来形成作用域链，在我们调用person方法时候才能访问，而直接访问是不能访问的，因为var定义的局部变量，所以我们取不到name的值而我们定义的函数getName里面return name;这个方法把name返回，在person方法里面也是一个return，所以我们可以通过getName的方法来访问person里面的name值。</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2020/06/10/JS%E4%B8%AD%E7%9A%84%E9%97%AD%E5%8C%85%E9%97%AE%E9%A2%98%EF%BC%8C%E9%97%AD%E5%8C%85%E7%9A%84%E9%82%A3%E6%98%AF%E4%BA%9B%E4%BA%8B/" data-id="ckd8udtbg00049gt41cvmg9et" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/js/" rel="tag">js</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2020/06/13/ES6%20Promise%E7%94%A8%E6%B3%95%E6%80%BB%E7%BB%93/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          ES6 Promise用法总结
        
      </div>
    </a>
  
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Vue/" rel="tag">Vue</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Vue%E5%85%A8%E5%AE%B6%E6%A1%B6/" rel="tag">Vue全家桶</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/js/" rel="tag">js</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/node/" rel="tag">node</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/Vue/" style="font-size: 20px;">Vue</a> <a href="/tags/Vue%E5%85%A8%E5%AE%B6%E6%A1%B6/" style="font-size: 10px;">Vue全家桶</a> <a href="/tags/js/" style="font-size: 15px;">js</a> <a href="/tags/node/" style="font-size: 10px;">node</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/07/">July 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/06/">June 2020</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2020/07/30/hello-world/">我的第一章博客</a>
          </li>
        
          <li>
            <a href="/2020/07/25/%E5%8E%9F%E7%94%9FHttp%E5%AE%9E%E7%8E%B0cookie%E8%AE%BE%E7%BD%AE/">原生Http实现cookie设置</a>
          </li>
        
          <li>
            <a href="/2020/07/23/%E5%B0%81%E8%A3%85Vue%E7%BB%84%E4%BB%B6%E5%B0%86%E4%BB%BB%E6%84%8F%E5%90%8E%E7%BC%80%E6%96%87%E4%BB%B6%E7%9B%AE%E5%BD%95%E7%BB%9F%E4%B8%80%E5%85%A8%E9%83%A8%E5%BC%95%E5%85%A5%E5%88%B0%E5%BD%93%E5%89%8D%E6%96%87%E4%BB%B6/">封装Vue组件将任意后缀文件目录统一全部引入到当前文件</a>
          </li>
        
          <li>
            <a href="/2020/07/15/js%E4%B8%AD%E7%9A%84%E9%98%B2%E6%8A%96%E4%B8%8E%E8%8A%82%E6%B5%81/">js中的防抖与节流</a>
          </li>
        
          <li>
            <a href="/2020/07/07/%E6%89%8B%E5%8A%A8%E5%AE%9E%E7%8E%B0call%EF%BC%8Capply,bind/">手动实现call，apply,bind</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2020 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  
<link rel="stylesheet" href="/fancybox/jquery.fancybox.css">

  
<script src="/fancybox/jquery.fancybox.pack.js"></script>




<script src="/js/script.js"></script>




  </div>
</body>
</html>